package com.ddone.oss.controller;

import com.ddone.common.exception.Assert;
import com.ddone.common.exception.BusinessException;
import com.ddone.common.result.Response;
import com.ddone.common.result.ResponseEnum;
import com.ddone.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ddone
 * @date 2024/4/16-09:48
 */
@RestController
@Api(tags = {"文件管理模块"})
// @CrossOrigin
@RequestMapping("/api/file")
public class FileController {

    @Resource
    private FileService fileService;


    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Response<String> upload(
            @ApiParam("需要上传的文件")
            @RequestParam(value = "file") MultipartFile file,
            @ApiParam(value = "文件所属模块",required = true)
            @RequestParam("module") String module) {

        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String uploadFileUrl = fileService.upload(inputStream, module, filename);

            Assert.notEmpty(module,ResponseEnum.DATA_IS_NOT_EMPTY);
            return Response.ok(uploadFileUrl).message("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }

    }

    @ApiOperation("按照URL删除文件")
    @DeleteMapping("/remove")
    public Response<Object> remove(
            @ApiParam(value = "要删除的文件路径",required = true)
            @RequestParam("url")
            String url){
        fileService.remove(url);
        return Response.ok().message("删除成功");
    }
}
